//
//  IdentificationCardViewController.m
//  dangdang
//
//  Created by air on 16/2/3.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "IdentificationCardViewController.h"
#import "ASIFormDataRequest.h"
#import "PersonalViewController.h"

@interface IdentificationCardViewController ()

@property (nonatomic, strong) UIView * backView;
@property (nonatomic, strong) UIView * buttonView;
@property (nonatomic, strong) UIView * lineView;
@property (nonatomic, strong) UIButton * topButton;
@property (nonatomic, strong) UIButton * bottomButton;
@property (nonatomic, strong) UIImageView * imageView;
@property (nonatomic, copy) NSString * string;
@property (nonatomic, strong) NSString * topPath;
@property (nonatomic, strong) NSString * middlePath;
@property (nonatomic, strong) NSString * bottomPath;
@property (nonatomic) NSInteger count;

@end

@implementation IdentificationCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _count = 0;
    
    [self updateUI];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(complete)];
    
    self.title = @"上传身份证";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)complete{
    if ([[NSFileManager defaultManager] fileExistsAtPath:_topPath] == NO){
        [self alertViewShowWithAlertString:@"请选择手持身份证正面照片"];
        return;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:_middlePath] == NO){
        [self alertViewShowWithAlertString:@"请选择身份证正面照片"];
        return;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:_bottomPath] == NO){
        [self alertViewShowWithAlertString:@"请选择身份证背面照片"];
        return;
    }
    
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * urlString = [NSString stringWithFormat:@"%@%@",URLDoman,@"courier/upload_ids"];
    
    UIImage * topImage = [[UIImage alloc] initWithContentsOfFile:_topPath];
    NSData * topData = UIImagePNGRepresentation(topImage);
    UIImage * middleImage = [[UIImage alloc] initWithContentsOfFile:_middlePath];
    NSData * middleData = UIImagePNGRepresentation(middleImage);
    UIImage * bottomImage = [[UIImage alloc] initWithContentsOfFile:_bottomPath];
    NSData * bottomData = UIImagePNGRepresentation(bottomImage);
    
    NSArray * dataArray = @[topData, middleData, bottomData];
    NSArray * nameArray = @[@"identificationTop.png", @"identificationMiddle.png", @"identificationBottom.png"];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    for (int i = 0; i < nameArray.count; i ++) {
        ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
        request.tag = 0x01;
        request.delegate = self;
        [request setRequestMethod:@"POST"];
        [request setTimeOutSeconds:90];
        [request addPostValue:token forKey:@"token"];
        //[request addPostValue:data forKey:@"attach"];
        [request addPostValue:userIDString forKey:@"uid"];
        [request addPostValue:[NSString stringWithFormat:@"%d", i] forKey:@"type"];
        [request addData:dataArray[i] withFileName:nameArray[i] andContentType:@"image/png" forKey:@"attach"];
        [request startAsynchronous];
    }
    
    PersonalViewController * personalboardVC = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalViewController"];
    
    personalboardVC.sucessIdentify = @"identify";
    
    [self.navigationController pushViewController:personalboardVC animated:YES];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    
//    _count ++;
//    NSString *resultDict=[[NSString alloc] initWithData:request.responseData encoding:request.responseEncoding] ;
//    if (_count == 3) {
//        PersonalViewController * personalboardVC = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalViewController"];
//        [self.navigationController pushViewController:personalboardVC animated:YES];
//    }
//    NSLog(@"result = %@", resultDict);
//    NSLog(@"上传头像返回");
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"上传头像失败");
}

//解析数据
- (NSMutableDictionary *)paramrequest:(ASIHTTPRequest *)request
{
    NSString *resultDict=[[NSString alloc] initWithData:request.responseData encoding:request.responseEncoding] ;
    NSDictionary *dict=[request userInfo];
    
    NSMutableDictionary *paramsDict=[[NSMutableDictionary alloc] init];
    if(resultDict!=nil)
    {
        [paramsDict setObject:resultDict forKey:@"Data"];
    }
    for(NSString *key in [dict allKeys])
    {
        [paramsDict setObject:[dict objectForKey:key] forKey:key];
    }
    return paramsDict;
}

- (void)updateUI{
    _scrollViewTopConstraint.constant -= 64;
    
    UITapGestureRecognizer * topTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushButton:)];
    topTap.numberOfTapsRequired = 1;
    _topView.tag = 1;
    [_topView addGestureRecognizer:topTap];
    
    UITapGestureRecognizer * middleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushButton:)];
    middleTap.numberOfTapsRequired = 1;
    _middleView.tag = 2;
    [_middleView addGestureRecognizer:middleTap];
    
    UITapGestureRecognizer * bottomTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushButton:)];
    bottomTap.numberOfTapsRequired = 1;
    _bottomView.tag = 3;
    [_bottomView addGestureRecognizer:bottomTap];
}

- (void)pushButton:(UITapGestureRecognizer *)tapGestureRecognizer{
    UIView * view = (UIView *)tapGestureRecognizer.view;
    _string = [NSString stringWithFormat:@"%ld", (long)view.tag];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeView)];
    tap.numberOfTapsRequired = 1;
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    _backView.backgroundColor = [UIColor colorWithRed:10/255.0 green:10/255.0 blue:10/255.0 alpha:0.2];
    [_backView addGestureRecognizer:tap];
    [self.view.window addSubview:_backView];
    
    _buttonView = [[UIView alloc] initWithFrame:CGRectMake(80, self.view.center.y - 50, [UIScreen mainScreen].bounds.size.width - 160, 101)];
    _buttonView.backgroundColor = [UIColor whiteColor];
    _buttonView.layer.cornerRadius = 8;
    [_backView addSubview:_buttonView];
    
    _topButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _buttonView.bounds.size.width, _buttonView.bounds.size.height / 2)];
    _topButton.tag = 1;
    [_topButton setTitle:@"相机" forState:UIControlStateNormal];
    [_topButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_topButton addTarget:self action:@selector(imageButton:) forControlEvents:UIControlEventTouchUpInside];    
    
    _bottomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _buttonView.bounds.size.height / 2 + 1, _buttonView.bounds.size.width, _buttonView.bounds.size.height / 2)];
    _bottomButton.tag = 2;
    [_bottomButton setTitle:@"相册" forState:UIControlStateNormal];
    [_bottomButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_bottomButton addTarget:self action:@selector(imageButton:) forControlEvents:UIControlEventTouchUpInside];
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, _buttonView.bounds.size.height / 2, _buttonView.bounds.size.width, 1)];
    _lineView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
    
    [_buttonView addSubview:_topButton];
    [_buttonView addSubview:_bottomButton];
    [_buttonView addSubview:_lineView];
}

- (void)removeView{
    [_backView removeFromSuperview];
}

- (void)imageButton:(UIButton *)button{
    if (button.tag == 1) {
        [_backView removeFromSuperview];
        
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }else if (button.tag == 2){
        [_backView removeFromSuperview];
        
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    NSData * imageData = UIImageJPEGRepresentation(currentImage, 1);
    //获取沙盒目录
    NSString * fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    //将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - 选择完成后调用该方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x - 150, 15, 300, 150)];
    
    //保存图片之本地，上传图片到服务器需要使用
    if ([_string isEqualToString:@"1"]) {
        [_topImageView removeFromSuperview];
        [_topLabel removeFromSuperview];
        
        [self saveImage:image withName:@"identificationTop.png"];
        
        _topPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"identificationTop.png"];
        
        UIImage * savedImage = [[UIImage alloc] initWithContentsOfFile:_topPath];
        
        //设置图片显示
        [_topView addSubview:_imageView];
        [_imageView setImage:savedImage];
    }else if ([_string isEqualToString:@"2"]) {
        [_middleImageView removeFromSuperview];
        [_middleLabel removeFromSuperview];
        
        [self saveImage:image withName:@"identificationMiddle.png"];
        
        _middlePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"identificationMiddle.png"];
        
        UIImage * savedImage = [[UIImage alloc] initWithContentsOfFile:_middlePath];
        
        //设置图片显示
        [_middleView addSubview:_imageView];
        [_imageView setImage:savedImage];
    }else if ([_string isEqualToString:@"3"]) {
        [_topImageView removeFromSuperview];
        [_topLabel removeFromSuperview];
        
        [self saveImage:image withName:@"identificationBottom.png"];
        
        _bottomPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"identificationBottom.png"];
        
        UIImage * savedImage = [[UIImage alloc] initWithContentsOfFile:_bottomPath];
        
        //设置图片显示
        [_bottomView addSubview:_imageView];
        [_imageView setImage:savedImage];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
